const Koa = require('koa');
const logger = require('koa-logger');
const registerRouter = require('./routes');
const cors = require('@koa/cors');
const bodyParser = require('koa-bodyparser')
const app = new Koa();
const Tools = new require('./tools');
const config = require('./config/config.js');
const tools = new Tools();
global.tools = tools;

app.use(cors()); //支持跨域请求
app.use(registerRouter());
app.use(bodyParser());
app.use(logger()); //记录日志


app.use(async (ctx, next) => {
  ctx.set('Content-Type', 'application/json');
  try {
    next();
    if (!ctx.body) { // 没有资源
      ctx.body = await tools.proxy(ctx);
    }
  } catch (e) {
    ctx.body = {
      code: 500,
      data: [],
      msg: '捕捉异常:' + e.message
    }
  }
});


//监听3000端口
app.listen(config.port, () => {
  console.log('server is running at http://localhost:3000')
});